﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Configuration;
using System.IO;

using FundSms.Client.BLL;
using FundSms.SmsLib;

namespace SmsClientMonitor
{
    public partial class Monitor : Form
    {
        private static Configuration config = null;
        private static KeyValueConfigurationCollection setting = null;
        //定时身份检查
        private static System.Timers.Timer timerSms = new System.Timers.Timer();
        //黑名单关键字刷新
        private static System.Timers.Timer timerService = new System.Timers.Timer();

        //服务所在路径
        private static string ServicePath = ConfigurationManager.AppSettings["ServicePath"];
        private static string ServiceName = ConfigurationManager.AppSettings["ServiceName"];

        private static bool bsms = false;
        private static bool bservice = false;

        private delegate void DlgSMS(SMS sms);
        private delegate void DlgSMSService(SmsService service);

        public Monitor()
        {
            InitializeComponent();

            this.Text = ServiceName;

            try
            {
                config = ConfigurationManager.OpenExeConfiguration(ServicePath);
                setting = config.AppSettings.Settings;
            }
            catch
            {
                MessageBox.Show("请确认Config文件中服务地址是否配置正确，加载失败","错误提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
                this.Close();
                return;
            }

            SMS sms = GetSms();
            BindDataSms(sms);

            SmsService service = GetSmsService();
            BindDataService(service);

            //InitializePanel();
            InitializeTabPage();
            InitializeTimer();
            
        }

        private void InitializeTabPage()
        {
            this.tabControl1.TabPages.Remove(this.tabPage2);
            this.tabControl1.TabPages.Remove(this.tabPage3);
        }

        private void BindDataSms(object o)
        {
            if (this.InvokeRequired)
            {
                DlgSMS bind = new DlgSMS(BindDataSms);
                this.Invoke(bind, new object[] { (SMS)o });
            }
            else
            {
                SMS sms = (SMS)o;

                this.lblDateTime.Text = DateTime.Now.ToString("yyyy-MM-dd");
                this.lblReturnCount.Text = sms.ReturnCount.ToString();
                this.lblSendCount.Text = sms.SendCount.ToString();
                this.lblUnReturnCount.Text = sms.UNReturnCount.ToString();
                this.lblWaitCount.Text = sms.UNSendCount.ToString();
            }
        }

        private void BindDataService(object o)
        {
            if (this.InvokeRequired)
            {
                DlgSMSService bind = new DlgSMSService(BindDataService);
                this.Invoke(bind, new object[] { (SmsService)o });
            }
            else
            {
                SmsService service = (SmsService)o;

                this.lblServiceName.Text = service.ServiceName;
                //this.lblServicePath.Text = ServicePath;
                this.lblServiceStatus.Text = service.ServiceStatus;
                this.btnService.Text = service.ServiceOperator;
                this.btnService.Enabled = service.IsEnable;
            }
        }

        private SMS GetSms()
        {
            SmsSendList send = new SmsSendList();
            SmsReturn ret = new SmsReturn();
            SMS sms = new SMS();

            try
            {
                sms.FailureCount = ret.GetFailureCount(DateTime.Now);
                sms.ReturnCount = ret.GetReturnCount(DateTime.Now);
                sms.SendCount = ret.GetSendCount(DateTime.Now);
                sms.SuccessCount = ret.GetSuccessCount(DateTime.Now);
                sms.UNReturnCount = ret.GetUnReturnCount(DateTime.Now);
                sms.UNSendCount = send.GetUnSendCount();
            }
            catch //(Exception e1)
            {
                //throw new Exception(e1.Message + "\r\n" + e1.StackTrace);
            }

            return sms;
        }

        private SmsService GetSmsService()
        {
            string servicename = GetValue("ServiceName");
            string displayname = GetValue("ServiceDisPlayName");

            SmsService service = new SmsService();
            service.ServiceName = displayname;


            if (!ServiceControl.CheckService(servicename))
            {
                service.ServiceOperator = "尚未安装";
                service.ServiceStatus = "尚未安装";
                service.IsEnable = false;
            }
            else
            {
                ServiceControllerStatus status = ServiceControl.GetServiceStatus(servicename);

                if (status == ServiceControllerStatus.Running)
                {
                    service.ServiceStatus = "正在运行";
                    service.ServiceOperator = "停止服务";
                    service.IsEnable = true;
                }
                else
                {
                    service.ServiceStatus = "已停止";
                    service.ServiceOperator = "启动服务";
                    service.IsEnable = true;
                }
            }

            return service;
        }

        private void InitializePanel()
        {
            if (GetValue("ClientDAL").IndexOf("Sql") >= 0)
            {
                this.cbDBType.SelectedIndex = 0;
                this.pnlMiddleOracle.Visible = false;
                this.pnlMiddleSql.Visible = true;
                this.pnlMiddleSql.Dock = DockStyle.Fill;
                
            }
            else
            {
                this.cbDBType.SelectedIndex = 1;
                this.pnlMiddleSql.Visible = false;
                this.pnlMiddleOracle.Visible = true;
                this.pnlMiddleOracle.Dock = DockStyle.Fill;
            }
        }

        private void InitializeTimer()
        {
            // 循环间隔时间(10分钟)
            timerSms.Interval = 5000;
            // 允许Timer执行
            timerSms.Enabled = true;
            // 定义回调
            timerSms.Elapsed += new System.Timers.ElapsedEventHandler(timerSms_Elapsed);
            // 定义多次循环
            timerSms.AutoReset = true;

            // 循环间隔时间(10分钟)
            timerService.Interval = 5000;
            // 允许Timer执行
            timerService.Enabled = true;
            // 定义回调
            timerService.Elapsed += new System.Timers.ElapsedEventHandler(timerService_Elapsed);
            // 定义多次循环
            timerService.AutoReset = true;
        }

        void timerService_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!bservice)
            {
                bservice = true;

                SmsService service = GetSmsService();

                BindDataService(service);

                bservice = false;
            }
        }

        void timerSms_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!bsms)
            {
                bsms = true;

                SMS sms = GetSms();

                BindDataSms(sms);

                bsms = false;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
            this.notifyIcon1.Visible = false; 
        }

        private void Monitor_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("您确认退出监控程序吗？", ServiceName, MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }

        }

        private void Monitor_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
                this.Visible = false;
                this.notifyIcon1.Visible = true;
                this.notifyIcon1.ShowBalloonTip(2000);
            } 

        }

        private string GetValue(string key)
        {
            return setting[key].Value;
        }

        private void SetValue(string key, string value)
        {
            setting[key].Value = value;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!bservice)
            {
                bservice = true;

                SmsService service = GetSmsService();

                BindDataService(service);

                bservice = false;
            }

            if (!bsms)
            {
                bsms = true;

                SMS sms = GetSms();

                BindDataSms(sms);

                bsms = false;
            }
        }

        private void cbDBType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbDBType.SelectedIndex == 0)
            {
                this.pnlMiddleOracle.Visible = false;
                this.pnlMiddleSql.Visible = true;
                this.pnlMiddleSql.Dock = DockStyle.Fill;

            }
            else
            {
                this.pnlMiddleSql.Visible = false;
                this.pnlMiddleOracle.Visible = true;
                this.pnlMiddleOracle.Dock = DockStyle.Fill;
            }
        }

        private void btnService_Click(object sender, EventArgs e)
        {
            string servicename = GetValue("ServiceName");
            ServiceControllerStatus status = ServiceControl.GetServiceStatus(servicename);

            if (this.btnService.Text == "启动服务")
            {
                if (status == ServiceControllerStatus.Stopped)
                {
                    ServiceControl.StartService(servicename);
                }
                else
                {
                    MessageBox.Show("操作进行中，请等候");
                }
            }
            else
            {
                if (status == ServiceControllerStatus.Running)
                {
                    ServiceControl.StopService(servicename);
                }
                else
                {
                    MessageBox.Show("操作进行中，请等候");
                }
            }
        }
    }

    internal class SMS
    {
        private int sendcount = 0 ;

        public int SendCount
        {
            get
            {
                return this.sendcount;
            }
            set
            {
                this.sendcount = value;
            }
        }

        private int unsendcount = 0;

        public int UNSendCount
        {
            get
            {
                return this.unsendcount;
            }
            set
            {
                this.unsendcount = value;
            }
        }

        private int returncount = 0;

        public int ReturnCount
        {
            get
            {
                return this.returncount;
            }
            set
            {
                this.returncount = value;
            }
        }

        private int unreturncount = 0;

        public int UNReturnCount
        {
            get
            {
                return this.unreturncount;
            }
            set
            {
                this.unreturncount = value;
            }
        }

        private int successcount = 0;

        public int SuccessCount
        {
            get
            {
                return this.successcount;
            }
            set
            {
                this.successcount = value;
            }
        }

        private int failurecount = 0;

        public int FailureCount
        {
            get
            {
                return this.failurecount;
            }
            set
            {
                this.failurecount = value;
            }
        }
    }

    internal class SmsService
    {
        private string servicename;

        public string ServiceName
        {
            get { return servicename; }
            set { servicename = value; }
        }

        private string servicestatus;

        public string ServiceStatus
        {
            get { return servicestatus; }
            set { servicestatus = value; }
        }

        private string serviceoperator;

        public string ServiceOperator
        {
            get { return serviceoperator; }
            set { serviceoperator = value; }
        }

        private bool isenable;

        public bool IsEnable
        {
            get { return isenable; }
            set { isenable = value; }
        }

        
    }

}